package com.shuaigef.springbootinit.controller;

import com.shuaigef.springbootinit.domain.Catalog;
import com.shuaigef.springbootinit.domain.req.CoverReq;
import com.shuaigef.springbootinit.domain.req.CreateReq;
import com.shuaigef.springbootinit.domain.req.StructureReq;
import com.shuaigef.springbootinit.domain.res.CoverRes;
import com.shuaigef.springbootinit.domain.res.PPTRes;
import com.shuaigef.springbootinit.utils.PPTUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/ppt")
public class PPTCreateController {
    @PostMapping("/structure")
    public List<Catalog> createPPT(@RequestBody StructureReq req){
        return PPTUtils.createStructure(req);
    }

    @PostMapping("/cover")
    public List<CoverRes> createCover(@RequestBody CoverReq req){
        return PPTUtils.createCover(req);
    }

    @PostMapping("/create")
    public String createPPT(@RequestBody CreateReq req){
        return PPTUtils.createPPT(req);
    }

    @PostMapping("status")
    public ResponseBodyEmitter getStatus(String id){
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        CompletableFuture.runAsync(()->{
            PPTRes result;
            do{
                result = PPTUtils.getResult(id);
                try {
                    emitter.send(result);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }while(result.getStatus() == 1);
        });
        return emitter;
    }

    @PostMapping("/download")
    public String downloadPPT(String id){
        return PPTUtils.downloadPPT(id);
    }
}
